<?php
namespace tp5_lib\user\model;

use think\Model;

/**
 * 处理手机验证码的模型
 * @property int $id
 * @property int $mobile
 * @property int $type
 * @property int $code
 * @property int $create_time 创建时间
 * @property int $status 0,新创建的;1,已经使用过;2,废弃
 */
class MobileCodeModel extends Model
{
    protected $table="user_mobile_code";
    public function install()
    {
        $table=$this->db()->getTable();
        $sql="CREATE TABLE IF NOT EXISTS `$table` (
            `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
            `mobile` varchar(20) NOT NULL,
            `type` varchar(20) NOT NULL,
            `code` varchar(10) NOT NULL,
            `create_time` int(11) NOT NULL,
            `status` int(11) NOT NULL
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
        $this->db()->execute($sql);
    }
    public function send($mobile,$type="")
    {
        $rand=rand(1000000,1999999);
        $rand=substr($rand,1);
        $data=[
            "mobile"=>$mobile,
            "type"=>$type,
            "code"=>$rand,
            "create_time"=>time(),
            "status"=>0
        ];
        $this->db()->where(["mobile"=>$mobile,"status"=>0])->setField("status",2);
        return $this->create($data);
    }
    public function check($mobile,$code,$type="",$expire=600)
    {
        /** @var self $record */
        $record=$this->db()->where(["mobile"=>$mobile,"type"=>$type,"status"=>0])->order("create_time desc")->find();
        if(!$record){
            $this->error="请先发送验证码";
            return false;
        }
        if($code!==$record->code){
            $this->error="验证码错误";
            return false;
        }

        if(time() > intval($record->create_time) + $expire){
            $this->error="验证码已超时，请重新发送";
            return false;
        }
        $this->db()->where(["id"=>$record->id])->setField("status",1);
        return $this;
    }
}
